﻿function Link(from, to, path) {
    var marker = document.getElementById("markerArrow");
    if (!marker) {
        svg.append('svg:marker')
        .attr('id', 'markerArrow')
        .attr('orient', 'auto')
        .attr('viewBox', '-5 -5 10 10')
        .attr('refX', 3)
        .attr('markerWidth', 7)
        .attr('markerHeight', 7)
        .append('svg:path')
        .attr('d', 'M 0,0 m -5,-5 L 5,0 L -5,5 Z')
        .attr('fill', '#000')
    }

    var padding = 20;
    //"[[142,175],[290,175]]"

    this.line = svg.append('path')
            .style('marker-end', 'url(#markerArrow)')
            .attr("stroke", "black")
            .attr("stroke-width", 1.5)
            .attr("fill", "none");

    BaseLine.apply(this, [this.line, null, null]);

    this._from = from;
    this._to = to;
    this._from.addLink(this);
    this._to.addLink(this);

    this._position = { x: JSON.parse(path)[0][0], y: JSON.parse(path)[0][1] };

    this.children = [];

    this.addChildren = function (node) {
        this.children.push(node);
        node._parent = this;
    }

    this.updateLayout = function () {
        if (this.logFlag) {
            worker.postMessage("Create a Line:  path:" + path);
        }
        this.logFlag = false;
        var that = this;
        this.line.attr("d", function (d) {
            var pathData = JSON.parse(path);
            var lineFunction = d3.svg.line()
                .x(function (d) {
                    that._position = { x: d[0], y: d[1] };
                    return that.getActualPosition(that._position).x;
                })
                .y(function (d) {
                    that._position = { x: d[0], y: d[1] };
                    return that.getActualPosition(that._position).y;
                })
                .interpolate("linear");
            return lineFunction(pathData);
        })
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].updateLayout();
        }
    }

    this.calcPath = function () {
        var f = this._from.getDomEl();
        var t = this._to.getDomEl();
        var point1 = this._from.getCenterPos();
        var point2 = this._to.getCenterPos();
        return " ";
    }

    this.hitTest = function (pos) {
        var point = JSON.parse(path);
        this._position = { x: point[0][0], y: point[0][1] };
        var firstPoint = this.getActualPosition({ x: point[0][0], y: point[0][1] });
        this._position = { x: point[point.length - 1][0], y: point[point.length - 1][1] };
        var lastPoint = this.getActualPosition({ x: point[point.length - 1][0], y: point[point.length - 1][1] });
        if (pos.x > firstPoint.x && pos.x < lastPoint.x && pos.y > lastPoint.y && pos.y < firstPoint.y) {
            return new HitResult(true, lastPoint.x - pos.x, firstPoint.y - pos.y);
        }
        return new HitResult(false, 0, 0);
    }
}